package com.ooqiu.gaming.ui.main.thread.video;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.api.entities.MainContentRes;
import com.ooqiu.gaming.base.BaseFragment;
import com.ooqiu.gaming.common.Constants;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.db.Channel;
import com.ooqiu.gaming.ui.channel.EditChannelActivity;
import com.ooqiu.gaming.ui.main.thread.common.ChannelPageAdapter;
import com.ooqiu.gaming.ui.main.thread.index.content.IndexContentAdapter;
import com.ooqiu.gaming.ui.search.SearchActivity;
import com.ooqiu.gaming.utils.LogUtil;
import com.ooqiu.greendao.ChannelDao;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
@Route(path = VideoFragment.PATH)
public class VideoFragment extends BaseFragment {
    public static final String PATH = "/fragment/video";
    @BindView(R.id.fake_status_bar)
    View mFakeStatusBar;

    @BindView(R.id.tab_channel)
    TabLayout mTabChannel;
    @BindView(R.id.img_add_channel)
    ImageView mImgAddChannel;
    @BindView(R.id.header_layout)
    LinearLayout mHeaderLayout;
    @BindView(R.id.page_index_content)
    ViewPager mPageIndexContent;


    GamingApi mGamingApi;
    @BindView(R.id.tv_search)
    TextView mTvSearch;

    boolean needRefreshCate = true;

    ChannelPageAdapter mChannelPageAdapter;
    List<Channel> mChannels = new ArrayList<>();
    Unbinder unbinder;

    UserStorage mUserStorage;
    ChannelDao mChannelDao;

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.e(intent.getAction());
            if (intent.getAction().equals(Constants.ACTION_KEYWORD_CHANGE)) {
                if (mTvSearch != null) {
                    mTvSearch.setText(intent.getBundleExtra("extra").getString("keyword"));
                }
            } else {
                needRefreshCate = true;
            }
        }
    };

    @Override
    public void initInjector(View view) {
        unbinder = ButterKnife.bind(this, view);
        mGamingApi = getApplicationComponent().getGamingApi();
        mUserStorage = getApplicationComponent().getUserStorage();
        mChannelDao = getApplicationComponent().getDaoSession().getChannelDao();
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_video;
    }


    @Override
    public void initUI(View view) {

//        mPageIndexContent.setAdapter(mChannelPageAdapter = new ChannelPageAdapter(getChildFragmentManager(), mChannels) {
//            @Override
//            public Fragment createFragment(Channel channel) {
//                return (BaseFragment) getRouter()
//                        .build(IndexContentFragment.PATH)
//                        .withParcelable(Constants.ROUTER_KEY_CHANNEL, channel)
//                        .navigation();
//            }
//        });
//        mTabChannel.setupWithViewPager(mPageIndexContent);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);


        mTabChannel.setupWithViewPager(mPageIndexContent);

        IntentFilter filter = new IntentFilter(Constants.ACTION_VIDEO_CATE_CHANGE);
        filter.addAction(Constants.ACTION_LOGIN_STATE_CHANGE);
        filter.addAction(Constants.ACTION_KEYWORD_CHANGE);
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, filter);


        fetchSearchWordFromNet();

    }

    @Override
    public void initData() {

    }


    @Override
    public boolean hasActionBar() {
        return true;
    }


    @Override
    protected View statusView() {
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void fetchMainContent() {
        mGamingApi.fetchVideoContent()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<MainContentRes>(mContext) {
                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onNext(MainContentRes mainContentRes) {
                        showContent();
                        mChannels.clear();
                        for (Channel channel : mainContentRes.getCategory()) {
                            channel.setShow(true);
                            channel.setModoule_id(Channel.MODULE_ID_VIDEO);
                        }
                        if (mChannelDao.queryBuilder().where(ChannelDao.Properties.Modoule_id.eq(Channel.MODULE_ID_VIDEO)).list().isEmpty() && !mUserStorage.isLogin()) {
                            mChannelDao.insertOrReplaceInTx(mainContentRes.getCategory());
                        }

                        mPageIndexContent.setAdapter(mChannelPageAdapter = new ChannelPageAdapter(getChildFragmentManager(), mUserStorage.isLogin() ? mainContentRes.getCategory() : mChannelDao.queryBuilder().where(ChannelDao.Properties.Show.eq(true), ChannelDao.Properties.Modoule_id.eq(Channel.MODULE_ID_VIDEO)).build().list()) {
                            @Override
                            public Fragment createFragment(Channel channel) {
                                return (BaseFragment) getRouter()
                                        .build(VideoContentFragment.PATH)
                                        .withParcelable(Constants.ROUTER_KEY_CHANNEL, channel)
                                        .navigation();
                            }
                        });
                        mPageIndexContent.setOffscreenPageLimit(mChannels.size());
                    }

                    @Override
                    public void handleError(Throwable e) {
                        if (e.getMessage().contains("Failed to connect")) {
                            showRetry("断网了,~T_T~请检查网络",R.mipmap.ic_net_disable);
                        } else {
                            showRetry(e.getMessage());
                        }
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (needRefreshCate) {
            needRefreshCate = false;
            fetchMainContent();
        }
    }


    @OnClick(R.id.img_add_channel)
    public void addChannel() {
        getRouter().build(EditChannelActivity.PATH)
                .withString("action", Constants.ACTION_VIDEO_CATE_CHANGE)
                .navigation();
    }


    @OnClick(R.id.tv_search)
    public void search() {
        getRouter().build(SearchActivity.PATH)
                .withInt("search_type", IndexContentAdapter.ITEM_VIDEO_CONTENT)
                .navigation();

    }


    private void fetchSearchWordFromNet() {
        mGamingApi.searchKeyWord(3)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<List<String>>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(List<String> strings) {
                        if (!strings.isEmpty()) {
                            mTvSearch.setText(strings.get(0));
                        }
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }
}
